package com.ruoyi.market.service.sms;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.db.entity.SmsConfigInfo;
import com.ruoyi.market.model.result.SmsInfoResult;
import com.ruoyi.market.service.ISmsInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class DaHanSmsInfoService implements ISmsInfoService {


    @Override
    public SmsInfoResult getSmsInfo(SmsConfigInfo smsConfigInfo) {

        SmsInfoResult smsInfoResult = new SmsInfoResult();
        smsInfoResult.setPlatformName("大汉");
        smsInfoResult.setSuccess(false);
        try {

//            String requestUrl = "http://www.dh3t.com/json/sms/Balance";
//            Map<String, Object> paramMap = new HashMap<>();
//            paramMap.put("account", "dh47239");
//            paramMap.put("password", "a814fc3270e904f33f7eef2df7975ef4");

            String requestUrl = smsConfigInfo.getQueryUrl();
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("account", smsConfigInfo.getAccount());
            paramMap.put("password", smsConfigInfo.getSecret());

            HttpRequest httpRequest = HttpUtil.createPost(requestUrl);
            String response = httpRequest.body(JSON.toJSONString(paramMap)).execute().body();
            log.info("【大汉短信服务】【余额查询】发送结束【requesturl】{}【paramMap】{}【bodyResult】{}",
                    smsConfigInfo.getUrl(), JSON.toJSONString(paramMap), response);

            JSONObject result = JSON.parseObject(response);
            String resultCode = result.getString("result");
            String desc = result.getString("desc");
            smsInfoResult.setCode(resultCode);
            smsInfoResult.setMessage(desc);

            if (StrUtil.equals(String.valueOf(resultCode), "0")){
                JSONObject smsBalance = result.getJSONObject("smsBalance");
                String amount = smsBalance.getString("amount");
                smsInfoResult.setBalance(amount);
                smsInfoResult.setSuccess(true);
            }
            return smsInfoResult;
        }catch (Exception exception){
            exception.printStackTrace();
            smsInfoResult.setCode("9999");
            smsInfoResult.setMessage(exception.getMessage());
        }
        return smsInfoResult;
    }
}
